﻿namespace TZBlog
{
    public interface IArticleDBAccess
    {
        List<ArticleEntity> GetList();
        ArticleEntity Get(string id);
        void Save(ArticleEntity entity);
        void Delete(string id);
    }
    public class ArticleDBAccess : DBAccessBase, IArticleDBAccess
    {
        public ArticleDBAccess(TZBlogDBContext context):base(context) { }

        public List<ArticleEntity> GetList()
        {
            return _context.Articles.ToList();
        }
        public ArticleEntity Get(string id) {
           return  _context.Articles.FirstOrDefault(t => t.F_Id == id);
        }
        public void Save(ArticleEntity entity) 
        {
            bool isAdd = true;
            if (!string.IsNullOrEmpty(entity.F_Id))
            {
                var obj=  Get(entity.F_Id);
                if (obj != null) {
                    obj.F_Status = entity.F_Status;
                    obj.F_Content = entity.F_Content;
                    obj.F_ConverImg= entity.F_ConverImg;
                    obj.F_Description= entity.F_Description;
                    obj.F_Title = entity.F_Title;
                    obj.Update();
                    _context.Update(obj);
                    isAdd = false;
                }                
            }
            if (isAdd)
            {
                entity.Create();
                _context.Add(entity);
            }
            _context.SaveChanges();
        }
        public void Delete(string id) {
            var obj = Get(id);
            if (obj != null) { 
                _context.Remove(obj);
                _context.SaveChanges();
            }
        }
    }
}
